package com.zyx.flinkdemo.sql.query;

import com.zyx.flinkdemo.pojo.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

/**
 * @author zyx
 * @since 2021/5/28 23:38
 * desc: 使用未注册的表进行查询
 */
public class TableUnregisteredQuery {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> waterSensorDs = env.socketTextStream("linux201", 7777)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String data) throws Exception {
                        String[] split = data.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 创建未注册的表
        Table table = tableEnv.fromDataStream(waterSensorDs);
        // 使用未注册的表进行查询
        Table result = tableEnv.sqlQuery("select id, sum(vc) from " + table + " group by id");

        tableEnv.toRetractStream(result, Row.class).print();

        env.execute();
    }
}
